package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if(dto==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"参数为空");
        }
        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> page1 = page(page, wrapper);
        // 3 返回结果

        return new PageResponseResult(dto.getPage(),dto.getSize(), page1.getTotal(),page1.getRecords());
    }


    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1 参数检查
       if (dto.getId()==null){
           throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"参数id为null");
       }

        //2 查询当前认证用户是否在 APP端有当前用户                                     where    .eq     id=5  and  name like '%zhangsan%'
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
       if (apUserRealname==null){
           throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
       }

       //判断是否为待审核
        if (apUserRealname.getStatus()!=1){
       throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"不为待审核状态");
        }
//根据实名关联的userid，查询apuser对象
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserRealname.getUserId()));
        if(apUser == null){

            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3 更新认证用户信息
      apUserRealname.setStatus(status);
       apUserRealname.setUpdatedTime(new Date());
       if (dto.getMsg()==null){
           apUserRealname.setReason(dto.getMsg());
       }
        updateById(apUserRealname);
        //4 认证状态如果为 通过
   if (status==9){
       //4.1 创建自媒体账户
       WmUser wmUser =  createWmUser(apUser);

       createApAuthor(wmUser);
   }


        //4.2 创建作者信息

        //5 返回结果
        return ResponseResult.okResult();
    }



    private WmUser createWmUser(ApUser apUser) {
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"调用失败");
        }

        WmUser wmUser = result.getData();
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"数据已存在");
        }
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(2); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(9);
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);

        return save.getData();
    }

    private void createApAuthor(WmUser wmUser) {
        ResponseResult<ApAuthor> byUserId = articleFeign.findByUserId(wmUser.getId());
        if (byUserId!=null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"作者信息已存在");
        }
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);

        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }

    }


}
